import Config from "app/config/Config";
import { AuthFailed, Forbbiden } from "app/core/HttpException";
import { Context } from "egg";
module.exports = () => {
    return async function (ctx: Context, next: () => Promise<any>) {

        if (Config.IGNORE_LOGIN_ROUTES.findIndex(v => v.test(ctx.path)) !== -1) {
            return await next()
        }

        const userToken = getToken(ctx)

        if (!userToken) {
            throw new Forbbiden('未登录！');
        }
        const userInfo = (await analyzeToken(userToken, ctx)) as { user_name, user_password }
        ctx.auth = {
            userInfo
        }
        await next()
    }
}
/**
 * 获取头部中的Token
 * @param ctx 
 * @returns 
 */
export function getToken(ctx: Context): string {
    return ctx.header['authorization']?.slice(7) || ctx.cookies.get('authorization')?.slice(7) || ''
}
/**
 * 验证token是否正确
 * @param token 
 * @param ctx 
 * @returns 
 */
async function analyzeToken(token: string, ctx: Context) {
    return new Promise((resolve, reject) => {
        ctx.app.jwt.verify(token, Config.SECURITY.SECRET_KEY, (error: Error, decode: any) => {
            if (error) reject(error);
            resolve(decode)
        })
    }).catch((error: Error) => {
        if (error.name === 'TokenExpiredError') {
            throw new AuthFailed('token已过期')
        }
        throw new Forbbiden('token不合法')
    })
}